﻿/******************************************************************************
 * SunnyUI 开源控件库、工具类库、扩展类库、多页面开发框架。
 * CopyRight (C) 2012-2022 ShenYongHua(沈永华).
 * QQ群：56829229 QQ：17612584 EMail：SunnyUI@QQ.Com
 *
 * Blog:   https://www.cnblogs.com/yhuse
 * Gitee:  https://gitee.com/yhuse/SunnyUI
 * GitHub: https://github.com/yhuse/SunnyUI
 *
 * SunnyUI.Common.dll can be used for free under the MIT license.
 * If you use this code, please keep this note.
 * 如果您使用此代码，请保留此说明。
 ******************************************************************************
 * 文件名称: UHotCache.cs
 * 文件说明: 热缓存类
 * 当前版本: V3.1
 * 创建日期: 2022-02-15
 *
 * 2022-02-15: V3.1.1 增加文件说明
******************************************************************************/

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace Sunny.UI
{
    public class HotCache<TKey, TValue> : BackgroundWorkerEx where TValue : class
    {
        protected override void DoWorker()
        {
            try
            {
                DateTime now = DateTime.Now;
                IList<TKey> removeList = new List<TKey>();
                foreach (HotCacheItem<TKey, TValue> obj in Cache.Values)
                {
                    TimeSpan span = now - obj.LastAccessTime;
                    if (span.TotalMinutes > AliveMinutes)
                    {
                        removeList.Add(obj.Key);
                    }
                }

                foreach (TKey id in removeList)
                {
                    Remove(id);
                }

                if (removeList.Count > 0)
                {
                    OnCacheChanged?.Invoke(this, EventArgs.Empty);
                }
            }
            catch
            {
            }
        }

        protected override void BeforeStop()
        {
            base.BeforeStop();
            Clear();
        }

        public event EventHandler OnCacheChanged;

        /// <summary>
        /// 对象存活时间（分钟）。如果一个对象在 AliveMinutes 时间间隔内都不被访问，则将被从缓存中清除。
        /// </summary>
        public int AliveMinutes { get; set; } = 5;

        public ConcurrentDictionary<TKey, HotCacheItem<TKey, TValue>> Cache = new ConcurrentDictionary<TKey, HotCacheItem<TKey, TValue>>();

        public bool ContainsKey(TKey key)
        {
            return Get(key) != null;
        }

        public void Add(TKey key, TValue value)
        {
            if (key == null) return;

            if (Cache.ContainsKey(key)) Cache.TryRemove(key, out _);
            Cache.TryAdd(key, new HotCacheItem<TKey, TValue>(key, value));
            OnCacheChanged?.Invoke(this, EventArgs.Empty);
        }

        public void Remove(TKey key)
        {
            if (key == null) return;

            if (Cache.ContainsKey(key))
            {
                Cache.TryRemove(key, out _);
                OnCacheChanged?.Invoke(this, EventArgs.Empty);
            }
        }

        public void Clear()
        {
            if (Cache.Count > 0)
            {
                Cache.Clear();
                OnCacheChanged?.Invoke(this, EventArgs.Empty);
            }
        }

        public TValue Get(TKey key)
        {
            if (key == null)
            {
                return null;
            }

            LastAccessTime = DateTime.Now;
            if (Cache.ContainsKey(key))
            {
                return Cache[key].Value;
            }

            var value = HotCacheItemCreator?.Run(key);
            if (value != null)
            {
                Add(key, value);
                return value;
            }

            return null;
        }

        public DateTime LastAccessTime { get; private set; }

        public IHotCacheItemCreator<TKey, TValue> HotCacheItemCreator { get; set; }
    }

    public interface IHotCacheItemCreator<TKey, TValue>
    {
        TValue Run(TKey key);
    }

    public class HotCacheItem<TKey, TValue>
    {
        public HotCacheItem(TKey key, TValue value)
        {
            Key = key;
            _value = value;
            LastAccessTime = DateTime.Now;
        }

        private TValue _value;

        public TKey Key { get; private set; }

        public TValue Value
        {
            get
            {
                LastAccessTime = DateTime.Now;
                return _value;
            }
        }

        public DateTime LastAccessTime { get; private set; }
    }
}
